package com.guo.hui.service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class InMessageInterceptor extends AbstractPhaseInterceptor<Message> {

	protected Logger log;

	public InMessageInterceptor() {

		this(Phase.RECEIVE, InMessageInterceptor.class.getName());
	}

	public InMessageInterceptor(String logName) {

		this(Phase.RECEIVE, logName);
	}

	protected InMessageInterceptor(String phase, String logName) {
		super(phase);
		log = Logger.getLogger(logName);
	}

	protected String modifyMessage(String message) {
		// message = "<SOAP-ENV:Envelope
		// xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns2:eRSSettStatusPushResponse
		// xmlns:ns2=\"com.ifs.ws.ers.m\"><ns2:msg>SUCCESS</ns2:msg><ns2:success>S</ns2:success><ns2:trackId>5f2db724-9dba-43c0-a694-1c3d82664fe7</ns2:trackId></ns2:eRSSettStatusPushResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";

		return message;
	}

	public void handleMessage(Message message) {
		try {

			String serviceName = "";
			Exchange exchange = message.getExchange();

			if (exchange != null && exchange.getService() != null)
				serviceName = exchange.getService().getName().toString();

			// log.info("Service = " + serviceName);

			InputStream is = message.getContent(InputStream.class);
			String encode = (String) message.get(Message.ENCODING);
			String xml = IOUtils.toString(is, encode);

			if (log.isInfoEnabled()) {
				log.info("Service = " + serviceName + ", soap message = " + xml);
			}

			xml = modifyMessage(xml);

			// if (log.isInfoEnabled()) {
			// log.info("final message = " + xml);
			// }

			message.setContent(InputStream.class, new ByteArrayInputStream(xml.getBytes(encode)));

		}

		catch (Exception e) {
			if (log.isEnabledFor(Level.DEBUG))
				log.error("Error when split original inputStream. CausedBy : " + "\n" + e);
		}
	}
}
